//
//  UIEdgeInsets+extension.swift
//  iUtil
//
//  Created by wendachuan on 19/3/22.
//  Copyright © 2019年 wendachuan. All rights reserved.
//

import UIKit

public extension UIEdgeInsets {
    /// 从字符串解析出UIEdgeInsets
    /// 字符串格式为: (0,0,0,0)
    ///
    /// - parameter insetsStr:
    init?(insetsStr: String) {
        self.init()
        do {
            let regex = try NSRegularExpression(pattern: "^\\s*\\(\\s*([0-9\\.]+)\\s*,\\s*([0-9\\.]+)\\s*,\\s*([0-9\\.]+)\\s*,\\s*([0-9\\.]+)\\s*\\)\\s*$", options: NSRegularExpression.Options.allowCommentsAndWhitespace)
            if let result = regex.firstMatch(in: insetsStr, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: insetsStr.count)) {
                if result.range.location != NSNotFound {
                    if result.numberOfRanges == 5 {
                        var numberArray = [Float]()
                        for index in 1 ..< 5 {
                            let xNSRange = result.range(at: index)
                            let xRange = insetsStr.index(insetsStr.startIndex, offsetBy: xNSRange.location) ..< insetsStr.index(insetsStr.startIndex, offsetBy: xNSRange.location + xNSRange.length)
                            let xStr = String(insetsStr[xRange])
                            let x = Float(xStr)
                            if x == nil {
                                return nil
                            }
                            numberArray.append(x!)
                        }
                        self.top = CGFloat(numberArray[0])
                        self.left = CGFloat(numberArray[1])
                        self.bottom = CGFloat(numberArray[2])
                        self.right = CGFloat(numberArray[3])
                    } else {
                        return nil
                    }
                } else {
                    return nil
                }
            } else {
                return nil
            }
        } catch {
            return nil
        }
    }
}
